package com.x.share.mid.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WxPayUtils {

	static Logger logger = LoggerFactory.getLogger(WxPayUtils.class);

	// 定义签名，微信根据参数字段的ASCII码值进行排序 加密签名,故使用SortMap进行参数排序
	public static String md5Sign(SortedMap<String, String> params, String key) {
		StringBuilder sb = new StringBuilder();
		Set<Entry<String, String>> es = params.entrySet();
		Iterator<Entry<String, String>> it = es.iterator();
		while (it.hasNext()) {
			Entry<String, String> entry = it.next();
			String k = entry.getKey();
			String v = entry.getValue();
			if (StringUtils.isNotBlank(v) && !k.equals("sign") && !k.equals("key")) {
				sb.append(k).append("=").append(v).append("&");
			}
		}
		sb.append("key=" + key);
		logger.info(">>>> params string: {}", sb.toString());
		String sign = DigestUtils.md5Hex(sb.toString()).toUpperCase();
		logger.info(">>>> sign string: {}", sign);
		return sign;
	}

	/**
	 * 微信支付参数转化为xml格式
	 * @param params
	 * @return
	 */
	public static String convert2Xml(SortedMap<String, String> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		Set<Entry<String, String>> es = params.entrySet();
		Iterator<Entry<String, String>> it = es.iterator();
		while (it.hasNext()) {
			Entry<String, String> entry = it.next();
			String k = entry.getKey();
			String v = entry.getValue();
			if ("sign".equalsIgnoreCase(k)) {
			} else if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k)) {
				sb.append("<").append(k).append(">").append("<![CDATA[").append(v).append("]]></").append(k)
						.append(">");
			} else {
				sb.append("<").append(k).append(">").append(v).append("</").append(k).append(">");
			}
		}
		sb.append("<sign>").append(params.get("sign")).append("</sign>");
		sb.append("</xml>");
		logger.info(">>>> request xml: {}", sb.toString());
		return sb.toString();
	}

	/**
	 * xml 转 Map
	 * 
	 * @param result
	 *            XML格式字符串
	 * @return
	 */
	public static Map<String, String> xml2Map(String result) {
		Map<String, String> map = new HashMap<String, String>();
		InputStream is = null;
		try {
			is = new ByteArrayInputStream(result.getBytes("utf-8"));
			SAXReader reader = new SAXReader();
			Document doc = reader.read(is);
			Element root = doc.getRootElement();
			@SuppressWarnings("unchecked")
			List<Element> list = root.elements();
			for (Element e : list) {
				map.put(e.getName(), e.getText());
			}
		} catch (Exception e) {
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
		}
		return map;
	}

	/**
	 * 获取随机串
	 * @param length
	 * @return
	 */
	public static String getNonceStr(int length) {
		String chars = "abcdefghijklmnopqrstuvwxyz0123456789";
		char[] str = new char[length];
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			int index = random.nextInt(chars.length());
			str[i] = chars.charAt(index);
		}
		return new String(str);
	}
	
	/**
	 * 微信异步通知流转化map
	 * @param stream
	 * @return
	 */
	public static Map<String, String> stream2Map(InputStream stream) {
		Map<String, String> map = new HashMap<String, String>();
		SAXReader reader = new SAXReader();
		try {
			Document doc = reader.read(stream);
			Element root = doc.getRootElement();
			@SuppressWarnings("unchecked")
			List<Element> list = root.elements();
			for (Element e : list) {
				map.put(e.getName(), e.getText());
			}
			stream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 将map转化为xml且不对参数做任务处理
	 * @param map
	 * @return
	 */
	public static String map2xmlInRaw(Map<String, String> map){
		String xmlResult = "";
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        for (String key : map.keySet()) {
            String value = "<![CDATA[" + map.get(key) + "]]>";
            sb.append("<" + key + ">" + value + "</" + key + ">");
        }
        sb.append("</xml>");
        xmlResult = sb.toString();
        logger.warn("wx pay notify >>>>> :[{}]", xmlResult);
        return xmlResult;
	}
}